package BFS;

import DFS.Graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Unweighted single source shortest path
 */
public class USSSPath {
    private Graph graph;
    private boolean[] visited;
    private int src;
    private int[] pre;
    public int[] dis;

    public USSSPath(Graph graph, int src) {
        this.graph = graph;
        this.src = src;
        this.visited = new boolean[this.graph.getVertexNum()];
        this.pre = new int[this.graph.getVertexNum()];
        this.dis = new int[this.graph.getVertexNum()];
        for (int i = 0; i < this.pre.length; i++) {
            this.pre[i] = -1;
            this.dis[i] = -1;
        }
        bfs(this.src);
        for (int i = 0; i < this.graph.getVertexNum(); i++) {
            System.out.print(dis[i] + " ");
        }
        System.out.println();
    }

    private void bfs(int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        this.visited[s] = true;
        this.pre[s] = s;
        dis[s] = 0;
        while (!queue.isEmpty()) {
            int v = queue.remove();
            for (int w : this.graph.adj(v)) {
                if (!this.visited[w]) {
                    queue.add(w);
                    this.visited[w] = true;
                    pre[w] = v;
                    dis[w] = dis[v] + 1;
                }
            }

        }
    }

    public boolean isConnectedTo(int dst) {
        graph.validateVertex(dst);
        return this.visited[dst];
    }

    public Iterable<Integer> path(int t) {
        List<Integer> res = new ArrayList<>();
        if (!isConnectedTo(t)) {
            return res;
        }
        int cur = t;
        while (cur != this.src) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(this.src);
        Collections.reverse(res);
        return res;
    }

    public int dis(int t) {
        graph.validateVertex(t);
        return dis[t];
    }

    public static void main(String[] a) {
        Graph g = new Graph("gDfs.txt");
        USSSPath bfs = new USSSPath(g, 0);
        System.out.println("0 -> 5 : " + bfs.isConnectedTo(5));
        System.out.println("0 -> 5 path : " + bfs.path(5));
    }
}